<template>
  <div v-loading="loading" class="p-4 pos-relative">
    <div v-loading="loading" class="block">
      <div class="task-block">
        <div class="block-title">新建任务</div>
        <el-form ref="taskFormRefs" :model="contentForm.taskForm" inline size="small" :rules="rules">
          <el-form-item label="任务名称" prop="loadExperimentName" label-width="70">
            <el-input
              v-model="contentForm.taskForm.loadExperimentName"
              placeholder="请输入"
              style="width: 180px"
              :disabled="contentForm.state !== '待创建'"
          /></el-form-item>
          <el-form-item label="机型" prop="modeType" label-width="70">
            <el-select
              v-model="contentForm.taskForm.modelType"
              clearable
              style="width: 180px"
              :disabled="contentForm.state !== '待创建'"
              @change="getpageVersions(contentForm.taskForm)"
            >
              <el-option v-for="(el, index) in pageAircraftTypes" :key="'modelType' + index" :label="el.label" :value="el.label" />
            </el-select>
          </el-form-item>
          <el-form-item label="载荷分类" prop="loadType" label-width="70">
            <el-select
              v-model="contentForm.taskForm.loadType"
              clearable
              style="width: 180px"
              :disabled="contentForm.state !== '待创建'"
              @change="getpageVersions(contentForm.taskForm, true)"
            >
              <el-option v-for="(el, index) in pageLoadTypes" :key="'name' + index" :label="el.label" :value="el.label" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="contentForm.taskForm.loadType" label="子分类" prop="subType" label-width="70">
            <el-select v-model="contentForm.taskForm.subType" clearable style="width: 180px" :disabled="contentForm.state !== '待创建'">
              <el-option v-for="(el, index) in pageSubTypes" :key="'name' + index" :label="el.label" :value="el.label" />
            </el-select>
          </el-form-item>
          <el-form-item label="阶段" prop="stage">
            <el-select
              v-model="contentForm.taskForm.stage"
              clearable
              style="width: 180px"
              :disabled="contentForm.state !== '待创建'"
              @change="getpageVersions(contentForm.taskForm)"
            >
              <el-option v-for="(el, index) in pageStages" :key="'stage' + index" :label="el.label" :value="el.label" />
            </el-select>
          </el-form-item>
          <el-form-item label="版本号" prop="loadcaseVersionId">
            <el-select
              v-model="contentForm.taskForm.loadcaseVersionId"
              style="width: 180px"
              clearable
              :disabled="contentForm.state !== '待创建'"
              @change="handleVersionChange"
            >
              <el-option v-for="(el, index) in pageVersions" :key="'stage' + index" :label="el.label" :value="el.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="轮次" prop="round">
            <el-select v-model="contentForm.taskForm.round" style="width: 180px" clearable :disabled="contentForm.state !== '待创建'">
              <el-option v-for="(el, index) in pageRounds" :key="'round' + index" :label="el.label" :value="el.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :disabled="contentForm.state !== '待创建'" @click="handleCreate">创建</el-button>
            <el-button :disabled="contentForm.state !== '待创建'" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="task-block mt-2">
        <div class="block-title">上传文件</div>
        <!-- 飞行垂向 -->
        <el-row v-if="contentForm?.taskForm?.loadType === '飞行垂向'" :gutter="10">
          <el-col :span="12">
            <TaskUpload
              key="1"
              v-model="contentForm.originalFileName"
              :disabled="contentForm.state !== '待开始'"
              name="ORIGINAL_LOAD"
              :load-experiment-id="contentForm.id"
              @update-file="updatedUploadFile('originalFileName')"
            />
            <TaskUpload
              key="2"
              v-model="contentForm.elevatorHingeCoordinateSystemInformation"
              :disabled="contentForm.state !== '待开始'"
              class="mt-2"
              name="elevator_hinge_coordinate_system_information_7_2"
              :load-experiment-id="contentForm.id"
              accept=".txt"
              title="升降舵铰链坐标系信息"
              @update-file="updatedUploadFile('elevatorHingeCoordinateSystemInformation')"
            />
          </el-col>
          <el-col :span="12">
            <TaskUpload
              key="3"
              v-model="contentForm.nodeInformationFileName"
              :disabled="contentForm.state !== '待开始'"
              name="NODE_INFO"
              :load-experiment-id="contentForm.id"
              accept=".dat"
              title="上传节点信息"
              @update-file="updatedUploadFile('nodeInformationFileName')"
            />
            <TaskUpload
              key="4"
              v-model="contentForm.nodeLoadNumberFileName"
              :disabled="contentForm.state !== '待开始'"
              name="NODE_LOAD_NUMBER"
              :load-experiment-id="contentForm.id"
              title="上传节点载荷编号"
              class="mt-2"
              accept=".txt"
              @update-file="updatedUploadFile('nodeLoadNumberFileName')"
            />
          </el-col>
        </el-row>
        <!--飞行侧向 -->
        <el-row v-else-if="contentForm?.taskForm?.loadType === '飞行侧向'" :gutter="10">
          <el-col :span="12">
            <TaskUpload
              key="1"
              v-model="contentForm.originalFileName"
              :disabled="contentForm.state !== '待开始'"
              name="ORIGINAL_LOAD"
              :load-experiment-id="contentForm.id"
              @update-file="updatedUploadFile('originalFileName')"
            />
            <TaskUpload
              key="2"
              v-model="contentForm.directionalRudderCoordinateSystemInformation"
              :disabled="contentForm.state !== '待开始'"
              class="mt-2"
              name="DIRECTIONAL_RUDDER_COORDINATE_SYSTEM_INFORMATION_7_2"
              :load-experiment-id="contentForm.id"
              accept=".txt"
              title="方向舵铰链坐标系信息"
              @update-file="updatedUploadFile('directionalRudderCoordinateSystemInformation')"
            />
          </el-col>
          <el-col :span="12">
            <TaskUpload
              key="3"
              v-model="contentForm.nodeInformationFileName"
              :disabled="contentForm.state !== '待开始'"
              name="NODE_INFO"
              :load-experiment-id="contentForm.id"
              accept=".dat"
              title="上传节点信息"
              @update-file="updatedUploadFile('nodeInformationFileName')"
            />
            <TaskUpload
              key="4"
              v-model="contentForm.nodeLoadNumberFileName"
              :disabled="contentForm.state !== '待开始'"
              name="NODE_LOAD_NUMBER"
              :load-experiment-id="contentForm.id"
              title="上传节点载荷编号"
              class="mt-2"
              accept=".txt"
              @update-file="updatedUploadFile('nodeLoadNumberFileName')"
            />
          </el-col>
        </el-row>
        <!-- 地面载荷、动突风、动着陆 -->
        <el-row
          v-else-if="
            contentForm?.taskForm?.loadType === '地面载荷' ||
            contentForm?.taskForm?.loadType === '动突风' ||
            contentForm?.taskForm?.loadType === '动着陆'
          "
          :gutter="10"
        >
          <el-col :span="12">
            <TaskUpload
              key="5"
              v-model="contentForm.originalFileName"
              :disabled="contentForm.state !== '待开始'"
              name="ORIGINAL_LOAD"
              :load-experiment-id="contentForm.id"
              @update-file="updatedUploadFile('originalFileName')"
            />
            <TaskUpload
              key="6"
              v-model="contentForm.cumulativeResult1G"
              :disabled="contentForm.state !== '待开始'"
              class="mt-2"
              name="CUMULATIVE_RESULT_1G"
              :load-experiment-id="contentForm.id"
              accept=".txt"
              title="1g累计结果"
              @update-file="updatedUploadFile('cumulativeResult1G')"
            />
          </el-col>
          <el-col :span="12">
            <TaskUpload
              key="7"
              v-model="contentForm.nodeInformationFileName"
              :disabled="contentForm.state !== '待开始'"
              name="NODE_INFO"
              :load-experiment-id="contentForm.id"
              accept=".dat"
              title="上传节点信息"
              @update-file="updatedUploadFile('nodeInformationFileName')"
            />
            <TaskUpload
              key="8"
              v-model="contentForm.nodeLoadNumberFileName"
              :disabled="contentForm.state !== '待开始'"
              name="NODE_LOAD_NUMBER"
              :load-experiment-id="contentForm.id"
              title="上传节点载荷编号"
              class="mt-2"
              accept=".txt"
              @update-file="updatedUploadFile('nodeLoadNumberFileName')"
            />
          </el-col>
        </el-row>
        <!-- 着路1g、突风1g、动滑行 -->
        <el-row v-else :gutter="10">
          <el-col :span="12">
            <TaskUpload
              key="9"
              v-model="contentForm.originalFileName"
              :disabled="contentForm.state !== '待开始'"
              height="267px"
              name="ORIGINAL_LOAD"
              :load-experiment-id="contentForm.id"
              @update-file="updatedUploadFile('originalFileName')"
            />
          </el-col>
          <el-col :span="12">
            <TaskUpload
              key="10"
              v-model="contentForm.nodeInformationFileName"
              :disabled="contentForm.state !== '待开始'"
              name="NODE_INFO"
              :load-experiment-id="contentForm.id"
              accept=".dat"
              title="上传节点信息"
              @update-file="updatedUploadFile('nodeInformationFileName')"
            />
            <TaskUpload
              key="11"
              v-model="contentForm.nodeLoadNumberFileName"
              :disabled="contentForm.state !== '待开始'"
              name="NODE_LOAD_NUMBER"
              :load-experiment-id="contentForm.id"
              title="上传节点载荷编号"
              class="mt-2"
              accept=".txt"
              @update-file="updatedUploadFile('nodeLoadNumberFileName')"
            />
          </el-col>
        </el-row>
        <!-- 自定义文件 -->
        <el-row :gutter="10">
          <el-col :span="24">
            <custom-file
              v-model="contentForm.uploadCustomizationFile"
              :disabled="contentForm.state !== '待开始'"
              class="mt-2"
              :load-experiment-id="contentForm.id"
              @update-file="updatedUploadFile('uploadCustomizationFile')"
            />
          </el-col>
        </el-row>
      </div>
      <div class="task-block mt-2">
        <div class="block-title">
          选择算法
          <el-button type="primary" style="margin-left: 20px" :disabled="tableDatas.length || contentForm.state !== '待开始'" @click="handleSelect"
            >选择</el-button
          >
        </div>
        <el-table v-if="tableDatas.length" :data="tableDatas">
          <el-table-column label="分析名" align="center" prop="analysis_type"></el-table-column>
          <el-table-column label="状态" align="center" prop="state"></el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="100">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="handleEditParams(scope.row)"
                >{{ contentForm.state !== '待开始' ? '查看' : '编辑' }}参数</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="btn-block">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" :loading="btnLoading" :disabled="contentForm.state !== '待开始'" @click="handleStartTask">开始任务</el-button>
        <el-button v-if="contentForm.state === '运行错误'" @click="handleViewLog">运行日志</el-button>
      </div>
    </div>
    <AlgorithmSelectDialog ref="algorithmSelectDialogRef" @on-sure="handleAlgorithmSure" />
    <EditParamsDialog ref="editParamsDialogRef" :disabled="contentForm.state !== '待开始'" />
    <RunLogDialog ref="runLogDialogRef" />
  </div>
</template>

<script setup name="loadTaskSubmission" lang="ts">
import TaskUpload from './taskUpload.vue';
import AlgorithmSelectDialog from './algorithmSelectDialog.vue';
import EditParamsDialog from './editParamsDialog.vue';
import CustomFile from './customFile.vue';
import { getAlgorithmList } from '@/api/loadProcessingAlgorithm/loadAlgorithmManagement/index';
import { getVersionList } from '@/api/loadProcessingAlgorithm/loadVersionManagement/index';
import {
  addExperiment,
  editExperiment,
  getExperimentDetail,
  startTask,
  getTaskInfoList,
  getExperimentList,
  addByHistory,
  taskLogList,
  asapDoCalculateLoad,
  asapGetTreeDataByAnalysis
} from '@/api/loadProcessingAlgorithm/loadTaskManagement/index';
import { loadNames, stages, aircraftTypes } from '@/api/loadProcessingAlgorithm/index';
import { caxConvertInfo } from '@/api/caxConversionPlatform/index';
import { constantRoutes } from '@/router/index';
import RunLogDialog from './runLogDialog.vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();
const editableTabsValue = ref(0);
const taskFormRefs = ref<ElFormInstance[]>([]);
const algorithmSelectDialogRef = ref();
const editParamsDialogRef = ref();
const runLogDialogRef = ref();
const loading = ref(true);
const btnLoading = ref(false);
const tableDatas = ref([]);
const timer = ref(null);
const pageSubTypes = ref([]);
const contentForm = reactive({
  id: '',
  title: '载荷实验',
  taskForm: {
    loadcaseVersionId: '',
    loadType: '',
    loadExperimentName: '',
    version: '',
    subType: '',
    stage: '',
    modelType: '',
    round: '',
    state: '待开始'
  },
  state: '待创建',
  historyLoadExperimentId: '',
  originalFileName: '',
  nodeInformationFileName: '',
  nodeLoadNumberFileName: '',
  cumulativeResult1G: '',
  uploadCustomizationFile: '',
  directionalRudderCoordinateSystemInformation: '',
  elevatorHingeCoordinateSystemInformation: ''
});
const pauseStep = ref(0);
const pauseNumber = ref(0);
const oldExperimentData = ref();
const rules = reactive({
  loadcaseVersionId: [{ required: true, message: '版本号不能为空', trigger: 'change' }],
  loadType: [{ required: true, message: '载荷分类不能为空', trigger: 'change' }],
  subType: [{ required: true, message: '子分类不能为空', trigger: 'change' }],
  loadExperimentName: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
  stage: [{ required: true, message: '阶段不能为空', trigger: 'change' }],
  modelType: [{ required: true, message: '机型不能为空', trigger: 'change' }],
  round: [{ required: true, message: '轮次不能为空', trigger: 'change' }]
});
const editableTabs = ref([]);
const editDialogShow = ref(false);
const pageLoadTypes = ref([]);
const pageStages = ref(stages);
const pageAircraftTypes = ref(aircraftTypes);
const pageVersions = ref([]);
const pageRounds = ref([]);
const getPageLoadTypes = () => {
  loadNames.forEach((item) => {
    pageLoadTypes.value = [...pageLoadTypes.value, ...item.children];
  });
};
const getpageVersions = async (data, flag?) => {
  if (flag && data.loadType) {
    const obj = pageLoadTypes.value.find((item) => item.label === data.loadType);
    if (obj) {
      pageSubTypes.value = obj.children;
      data.subType = '';
    }
  }
  if (data.loadType && data.stage && data.modelType) {
    const obj = {
      pageNum: 1,
      pageSize: 99,
      modelType: data.modelType,
      loadType: data.loadType,
      stage: data.stage,
      state: '使用中'
    };
    const res = await getVersionList(obj);
    if (!res?.rows?.length) {
      data.loadcaseVersionId = '';
      pageVersions.value = [];
      return false;
    }
    pageVersions.value = res?.rows?.map((item) => {
      return {
        value: item.id,
        label: item.version,
        loadName: item.loadName
      };
    });
  } else {
    data.loadcaseVersionId = '';
  }
};
const getpageRounds = async (data) => {
  if (data.loadType && data.stage && data.modelType && data.version) {
    const obj = {
      pageNum: 1,
      pageSize: 99,
      modelType: data.modelType,
      loadType: data.loadType,
      stage: data.stage,
      version: data.version,
      state: '使用中'
    };
    const res = await getVersionList(obj);
    if (!res?.rows?.length) {
      data.round = '';
      pageRounds.value = [];
      return false;
    }
    pageRounds.value = res?.rows?.map((item) => {
      return {
        value: item.round,
        label: item.round
      };
    });
  } else {
    data.loadcaseVersionId = '';
  }
};
const handleVersionChange = (value) => {
  const obj = pageVersions.value.find((item) => item.value === value);
  if (obj) {
    contentForm.taskForm.version = obj.label;
    contentForm.taskForm.loadName = obj.loadName;
    getpageRounds(contentForm.taskForm);
  }
};
const handleCreate = async () => {
  const el = taskFormRefs.value;
  await el.validate(async (valid, fields) => {
    if (valid) {
      contentForm.state = '待开始';
      const res = await addExperiment(contentForm.taskForm).catch(() => {
        contentForm.state = '待创建';
      });
      contentForm.id = res.data;
      proxy?.$modal.msgSuccess('创建成功！');
    } else {
      proxy?.$modal.msgError('请填写完成信息！');
    }
  });
};

const handleReset = () => {
  const el = taskFormRefs.value;
  el.resetFields();
};
const updatedUploadFile = async (name) => {
  const newObj = {
    id: contentForm.id,
    loadcaseVersionId: contentForm.taskForm.loadcaseVersionId,
    loadType: contentForm.taskForm.loadType,
    loadExperimentName: contentForm.taskForm.loadExperimentName,
    stage: contentForm.taskForm.stage,
    state: '待开始'
  };
  newObj[name] = contentForm[name];
  await editExperiment(newObj); // 保存上传文件
};
const handleAlgorithmSure = (data) => {
  tableDatas.value = [
    {
      task_id: contentForm.id,
      version_id: contentForm.taskForm.loadcaseVersionId,
      analysis_type: data.analysis_type,
      state: contentForm.state
    }
  ];
};
const handleSelect = () => {
  if (!contentForm.id) {
    proxy?.$modal.msgWarning('请先创建实验！');
    return false;
  }
  algorithmSelectDialogRef.value.openDialog(contentForm);
};
const handleEditParams = (data) => {
  editParamsDialogRef.value.openDialog(data);
};
const handleClose = () => {
  router.push({ path: '/loadTaskManagement' });
};
const getTaskResult = async () => {
  const obj = {
    id: contentForm.id,
    pageSize: 99,
    pageNum: 1
  };
  const res = await getExperimentList(obj);
  const datas = res.rows;
  if (datas.length) {
    const item = datas[0];
    if (item.state === '已完成') {
      if (timer.value) {
        proxy?.$modal.msgSuccess('运行完成！');
        clearInterval(timer.value);
      }
    } else if (item.state === '运行错误') {
      if (timer.value) {
        proxy?.$modal.msgSuccess('运行错误！');
        clearInterval(timer.value);
      }
    }
    const newObj = tableDatas.value[0];
    newObj.state = item.state;
    contentForm.state = item.state;
  }
};
const handleStartTask = async () => {
  btnLoading.value = true;
  const obj = {
    task_id: String(contentForm.taskForm.loadcaseVersionId),
    node_id_list: [String(contentForm.id)]
  };
  asapDoCalculateLoad(obj)
    .then((res) => {
      timer.value = setInterval(async () => {
        getTaskResult();
      }, 5000);
      btnLoading.value = false;
      proxy?.model.msgSuccess('任务开始！');
    })
    .catch(() => {
      btnLoading.value = false;
    });
};
const handleViewLog = () => {
  runLogDialogRef.value.openDialog(contentForm.id);
};
const getAlgorithmData = (id) => {
  const obj = {
    task_id: id
  };
  asapGetTreeDataByAnalysis(obj).then((res) => {
    if (res.data.length) {
      const type = res.data[0];
      tableDatas.value = [
        {
          task_id: contentForm.id,
          version_id: contentForm.taskForm.loadcaseVersionId,
          analysis_type: type,
          state: contentForm.state
        }
      ];
    }
  });
};
const setData = async (id) => {
  const res = await getExperimentDetail(String(id));
  const datas = res.data;
  contentForm.id = datas.id;
  contentForm.title = datas.loadExperimentName;
  contentForm.taskForm.loadcaseVersionId = datas.loadcaseVersionId;
  contentForm.taskForm.loadType = datas.loadType;
  contentForm.taskForm.loadExperimentName = datas.loadExperimentName;
  contentForm.taskForm.stage = datas.stage;
  contentForm.taskForm.state = datas.state;
  contentForm.taskForm.subType = datas.subType;
  contentForm.taskForm.modelType = datas.modelType;
  contentForm.taskForm.round = datas.round;
  contentForm.taskForm.loadName = datas.loadName;
  contentForm.state = datas.state;
  contentForm.uploadCustomizationFile = datas.uploadCustomizationFile;
  contentForm.historyLoadExperimentId = datas.historyLoadExperimentId;
  contentForm.originalFileName = datas.originalFileName;
  contentForm.cumulativeResult1G = datas.cumulativeResult1G;
  contentForm.nodeInformationFileName = datas.nodeInformationFileName;
  contentForm.nodeLoadNumberFileName = datas.nodeLoadNumberFileName;
  contentForm.directionalRudderCoordinateSystemInformation = datas.directionalRudderCoordinateSystemInformation;
  contentForm.elevatorHingeCoordinateSystemInformation = datas.elevatorHingeCoordinateSystemInformation;
  getpageVersions(contentForm.taskForm);
  getAlgorithmData(id);
  if (contentForm.state === '运行中') {
    timer.value = setInterval(async () => {
      getTaskResult();
    }, 5000);
  }
};
const initData = async () => {
  loading.value = true;
  const id = route.params.id;
  if (id) {
    setData(id);
    loading.value = false;
    return false;
  }
  loading.value = false;
};
onMounted(async () => {
  loading.value = true;
  await initData();
  await getPageLoadTypes();
  loading.value = false;
});
onActivated(async () => {
  loading.value = true;
  await initData();
  await getPageLoadTypes();
  loading.value = false;
});
</script>

<style lang="scss" scoped>
.task-block {
  border: 1px solid #e4e4e4;
  padding: 12px;
}
.block-title {
  font-size: 14px;
  font-weight: 600;
  padding-bottom: 12px;
}
.btn-block {
  padding-top: 12px;
  text-align: center;
}
</style>
